package com.example.webchar.webchar.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

import static com.example.webchar.webchar.utils.JwtUtil.subStringToken;

/**
 * @program: boot
 * @description
 * @author: YouName
 * @create: 2021-03-24 11:55
 **/
@Slf4j
public class JwtFilter extends BasicHttpAuthenticationFilter {


    /**
     * 判断用户是否想要登入。
     * 检测header里面是否包含token字段即可
     * 判断token是否为空
     */
    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        try {
            HttpServletRequest req = (HttpServletRequest) request;
            String token = subStringToken(req);
            return true;
        } catch (Exception e) {
            response401(request, response);
            return false;
        }
    }

    /**
     * 判断用户是否验证成功
     * login不验证
     * 判断验证验证是否正确
     */
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) {
        try {
            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            JwtToken token = new JwtToken(subStringToken(httpServletRequest));
            getSubject(request, response).login(token);
            return true;
        } catch (Exception e) {
            response401(request, response);
            return false;
        }
    }

    private void response401(ServletRequest req, ServletResponse resp) {
        try {
            req.getRequestDispatcher("/user/401").forward(req, resp);
            return;
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}


